package cn.itsource.basic.utils;

import cn.itsource.basic.jwt.JwtUtils;
import cn.itsource.basic.jwt.Payload;
import cn.itsource.basic.jwt.RsaUtils;
import cn.itsource.basic.jwt.UserInfo;
import cn.itsource.org.domain.Logininfo;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.PublicKey;

/**
 * 获取当前登录人信息
 */
public class LoginContext {

    public static final String JWT_RSA_PUBLIC = "hrm_auth_rsa.pub";

    public static Logininfo getCurrentUser(HttpServletRequest request){
        //从请求中获取token
        try {
            String token = request.getHeader("U-TOKEN");//json web token
            //获取公钥
            PublicKey publicKey = RsaUtils
                    .getPublicKey(FileCopyUtils
                            .copyToByteArray(LoginContext.class.getClassLoader().getResourceAsStream(JWT_RSA_PUBLIC)));
            //解密获取payload对象
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            return userInfo.getLogininfo();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
